package j.framework.tags.form;

import j.framework.tags.TagUtils;
import j.util.DES;
import j.util.StringUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * form隐藏域，可指定是否加密
 * User: jason
 * Date: 2014/12/18 9:07
 */
public class HiddenTag extends TagSupport {
    private String name;
    private String value;
    private boolean encrypted = false;

    @Override
    public int doStartTag() throws JspException {
        FormTagWriter writer;
        FormTag formTag = TagUtils.getParentAsFormTag(this);
        String hiddenValue = value;
        if(null!=formTag){
            writer = formTag.getWriter();
            if(StringUtils.isNullOrEmpty(hiddenValue)) {
                Object obj = formTag.getFormDataValue(name);
                if(obj!=null){
                    hiddenValue = String.valueOf(formTag.getFormDataValue(name));
                }
            }
        }else{
            writer = new FormTagWriter(this.pageContext.getOut());
        }
        writer.beginTag("input");
        writer.writeFormTagProperty("type", "hidden");
        writer.writeFormTagProperty("id", name);
        writer.writeFormTagProperty("name", name);
        if(StringUtils.isNotEmpty(hiddenValue)){
            if(encrypted){
                hiddenValue = DES.encrypt(hiddenValue);
            }
            writer.writeFormTagProperty("value", hiddenValue);
        }
        writer.closeBlankTag();
        writer.flush();
        return EVAL_PAGE;
    }



    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setEncrypted(boolean encrypted) {
        this.encrypted = encrypted;
    }
}
